<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Audio Stream with MediaSource</title>
</head>
<body>

<script src="./js/pcmPlayer.js"></script>
<script>

        var player = new PCMPlayer({
            encoding: "16bitInt",
            channels: 1,
            sampleRate: 22050,
            flushingTime: 180
        });

        // 音频流的 URL
        const audioStreamUrl = "http://127.0.0.1:8081/sse/mitter/stream-sse-sink";
        fetchAudioData()

        function fetchAudioData() {
            fetch(audioStreamUrl) // 替换为你的音频流URL
                .then(response => response.body.getReader())
                .then(reader => {
                    let tempResult = ''
                    function read() {
                        reader.read().then(({ done, value }) => {
                            if (done) {return;}

                            const decoder = new TextDecoder('utf-8')
                            let str = decoder.decode(value, {stream: true})
                            tempResult += str
                            const split = tempResult.match(/data:.*}\n\n/g)

                            if (split) {
                                str = split.join('')
                                tempResult = tempResult.replace(str, '')
                            } else {
                                return read()
                            }

                            if (str && str.startsWith('data:')) {
                                if (split) {
                                    for (const index in split) {
                                        const chunk = JSON?.parse(split[index].replace('data:', ''))

                                        let uint8Array = Uint8Array.from(atob(chunk.data), (c) => c.charCodeAt(0));
                                        console.log("test",chunk,uint8Array,typeof uint8Array.buffer)


                                        player.feed(uint8Array)
                                    }
                                }
                            }

                            read();
                        });
                    }
                    read();
                }).catch(error => {
                console.error('Fetching audio data failed:', error);
            });
        }

</script>
</body>
</html>